package com.iofile.service;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iofile.jianwei.OtherService;
import com.iofile.utils.FileUtilCyw;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import org.apache.commons.io.FileUtils;
import org.springframework.util.ObjectUtils;

/**
 * @Author: Chenyw
 * @Date: 2022/08/08/15:52
 */
@Service
@SuppressWarnings("all")
public class InitService {

    @Value("${url}")
    private String url;

    @Value("${suyuanUrl}")
    private String suyuanUrl;

    @Value("${type}")
    private String type;


    @Value("${registerPerson}")
    private String registerPerson;

    @Value("${registerAudioUrl}")
    private String registerAudioUrl;



    /**
     * 鉴伪->输出结果文件
     */
    //@PostConstruct
    public void fileParseJianweiSplit() {
        System.out.println("鉴伪->开始");

        File file = new File("/home/chenyanwei/result/jianweiResult" + File.separator + type + File.separator + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) + ".txt");
        List<String> allFile = FileUtilCyw.getAllFile(url, false);
        allFile.forEach(
                filePath -> {
                    JSONObject jsonObject = JSONObject.parseObject(OtherService.getJianweiResult(filePath));
                    double prob = Double.parseDouble(jsonObject.getString("prob"));
                    if (prob < 0.8) {
                        try {
                            FileUtils.write(file, filePath + " " + "true" + "\n", "UTF-8", true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            FileUtils.write(file, filePath + " " + "false" + "\n", "UTF-8", true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                }
        );
        System.out.println("鉴伪->完成");
    }

    int i = 0;
    /**
     * 注册特定人
     */
    @PostConstruct
    public void speakerRegister() throws IOException {
        List<String> allFile = FileUtilCyw.getAllFile(url, false);
        System.out.println("==============================注册特定人"+registerPerson+"==========================================");
        JSONObject jsonObject = JSONObject.parseObject(OtherService.register(registerAudioUrl, registerPerson));
        System.out.println(jsonObject);
        System.out.println("==============================完成==========================================");


        for (int j = 1; j <= allFile.size(); j++) {
            System.out.println(computeRegister(allFile.get(j - 1)) + j);
        }
//
//
//
//        if (allFile.size() > 50) {
//            for (int j = 1; j <= allFile.size(); j++) {
//                System.out.println(computeRegister(allFile.get(j - 1)));
//            }
//        }else {
//            for (int j = 1; j <= allFile.size(); j++) {
//                System.out.println(computeRegister(allFile.get(j - 1)));
//            }
//        }


        System.out.println("特定人筛选生效->" + registerPerson);
        JSONObject jsonObject1 = JSONObject.parseObject(OtherService.speakerScope(registerPerson));
        System.out.println(jsonObject1);
        System.out.println("特定人筛选生效->完成");

        //shengwenSplit();
        fileParseJianweiSplit();
    }


    /**
     * 声纹->输出结果文件
     */
    public void shengwenSplit() throws IOException {
        System.out.println("声纹->开始");
        File file = new File("/home/chenyanwei/result/shengwenResult" + File.separator + type + File.separator + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) + ".txt");
        File fileResult = new File("/home/chenyanwei/result/shengwenResult" + File.separator + type + File.separator + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) + File.separator + registerPerson + "countResult" + ".txt");
        List<String> allFile = FileUtilCyw.getAllFile(url, false);
        FileUtils.write(fileResult, "识别出来的声纹音频如下:" + "\n", "UTF-8", true);
        allFile.forEach(
                filePath -> {
                    JSONObject jsonObject = JSONObject.parseObject(OtherService.getShengwenResult(filePath));
                    if (!ObjectUtils.isEmpty(jsonObject)) {
                        String shengwen = jsonObject.getString("data");
                        if (registerPerson.equals(shengwen)) {
                            try {
                                i++;
                                FileUtils.write(fileResult, filePath + "\n", "UTF-8", true);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            FileUtils.write(file, filePath + " " + shengwen + "\n", "UTF-8", true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.println(filePath + "jsonObject==null");
                    }
                }
        );
        FileUtils.write(fileResult, "共有音频数量:" + allFile.size() + "\n", "UTF-8", true);
        FileUtils.write(fileResult, "识别出的音频数量:" + i + "\n", "UTF-8", true);
        FileUtils.write(fileResult, "未识别出的音频数量:" + (allFile.size() - i) + "\n", "UTF-8", true);


        System.out.println("声纹->完成");
    }


    /**
     * 返回音频特征同时更新
     */
    public String computeRegister(String audioUrl) {
        return OtherService.updateSpeaker(registerPerson, JSONObject.parseObject(OtherService.computeRegister(audioUrl)).getString("data"));
    }


    /**
     * 溯源->输出结果文件
     */


    int suyuanNum = 0;
    //@PostConstruct
    public void suyuan() throws IOException {
        System.out.println("溯源->开始");
        Map<String, List<String>> map = new HashMap<>();
        File file = new File("/home/chenyanwei/result/suyuanResult"  + File.separator + new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss").format(new Date()) + ".txt");
        List<String> allFile = FileUtilCyw.getAllFile(suyuanUrl, false);
        FileUtils.write(file, "识别出来的溯源音频如下:" + "\n", "UTF-8", true);

        allFile.forEach(
                filePath -> {
                    String suffix = FileUtil.getPrefix(filePath);
                    String suName =suffix.substring(0, suffix.lastIndexOf("_", suffix.lastIndexOf("_") - 1) - 1);
                    List<String> listResult = new ArrayList<>();
                    if (map.containsKey(suName)){
                        List<String> list = map.get(suName);
                        listResult.addAll(list);
                    }

                    JSONObject jsonObject = JSONObject.parseObject(OtherService.suyuan(filePath));
                    listResult.add(JSONObject.parseObject(OtherService.suyuan(filePath)).toJSONString());
                    map.put(suName,listResult);


                    System.out.println("========================名="+suName+"=================");
                    System.out.println(suyuanNum++);
                }
        );
        map.forEach((key, value) -> {
            System.out.println(key + "：" + value);
            try {
                FileUtils.write(file, "音频名:"+key+"\n", "UTF-8", true);
                FileUtils.write(file, "溯源结果:"+"\n", "UTF-8", true);
                FileUtils.write(file, value+"\n", "UTF-8", true);
            } catch (IOException e) {
                e.printStackTrace();
            }

        });

        System.out.println(map.size());
        System.out.println("溯源->完成");
    }

    public static void main(String[] args) {

            String	path = "d:\\aaa\\bbb_cc_abcd_efghig_klmn.jpg";
            //返回主文件名
            String suffix = FileUtil.getPrefix(path);
        String substring1 = suffix.substring(0, suffix.lastIndexOf("_", suffix.lastIndexOf("_") - 1) - 1);
        int i = suffix.lastIndexOf("_");
        String substring = suffix.substring(0, i);
        System.out.println(substring1);

    }

    @Async
    public void saveLog() {
        System.err.println(Thread.currentThread().getName());
    }

}
